import * as cheerio from 'cheerio';
import puppeteer from 'puppeteer-core';
import { Inject, Injectable } from '@nestjs/common';
import { LogService } from '../log/log.service';

@Injectable()
export class SpiderService {
  @Inject(LogService)
  private readonly logger: LogService;

  async spiderBaiduAi(word: string, mode: 'deep' | 'DS-R1' = 'deep', maxRetries: number = 3) {
    let attempt = 0;

    while (attempt < maxRetries) {
      attempt++;
      this.logger.info(`${word}：第${attempt}次尝试`);

      const browser = await puppeteer.launch({
        executablePath: process.env.PUPPETEER_EXECUTABLE_PATH || 'C:/Program Files/Google/Chrome/Application/chrome.exe',
        headless: true,
        args: [
          '--no-sandbox',
          '--disable-setuid-sandbox',
          '--disable-dev-shm-usage',
          '--disable-accelerated-2d-canvas',
          '--no-first-run',
          '--no-zygote',
          '--disable-gpu',
        ],
      });
      const page = await browser.newPage();

      // 设置 User-Agent 模拟真实浏览器
      await page.setUserAgent(
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
      );

      // 设置其他浏览器特征
      await page.setViewport({ width: 1366, height: 768 });
      await page.setExtraHTTPHeaders({
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
        Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
      });

      try {
        // 访问网站
        await page.goto(`https://chat.baidu.com/search`, {
          // await page.goto(`https://chat.baidu.com/search?word=${word}`, {
          waitUntil: 'networkidle2',
          timeout: 4 * 60 * 1000,
        });

        // 获取页面标题
        const title = await page.title();

        // 点击深度搜索按钮
        switch (mode) {
          case 'deep':
            try {
              await page.waitForSelector('.deep-search-icon', { timeout: 10000 });
              await page.click('.deep-search-icon');
            } catch (error) {
              this.logger.warn(`未找到深度搜索按钮: ${error.message}`);
            }
            break;
          case 'DS-R1':
            await page.waitForSelector('.deep-search-icon', { timeout: 10000 });
            await page.click('.model-network-select');
            break;
        }

        // 等待三秒
        await new Promise((resolve) => setTimeout(resolve, 3000));

        // 输入框搜索
        try {
          // 等待并定位到 textarea 输入框
          await page.waitForSelector('#chat-textarea', { timeout: 10000 });

          // 清空输入框并输入搜索内容
          await page.focus('#chat-textarea');
          await page.keyboard.down('Control');
          await page.keyboard.press('KeyA');
          await page.keyboard.up('Control');
          await page.keyboard.press('Backspace');

          // 输入搜索词
          await page.type('#chat-textarea', word);

          // 等待一下让输入完成
          await new Promise((resolve) => setTimeout(resolve, 1000));

          await new Promise((resolve) => setTimeout(resolve, 3000));

          // 按回车键提交搜索
          await page.keyboard.press('Enter');
        } catch (error) {
          this.logger.warn(`输入框搜索失败: ${error.message}`);
        }

        // 等待30秒
        await page.waitForSelector('div[data-module="ai_questionClosely"]', {
          timeout: 4 * 60 * 1000,
        });

        // 获取页面HTML
        const html = await page.content();
        const content = this.solveBaiduContent(html);

        // console.log('content', content);
        // await new Promise((resolve) => setTimeout(resolve, 1000 * 60 * 60));
        await browser.close();

        // 如果成功获取到内容，直接返回
        if (content && content.length > 0) {
          this.logger.info(`${word}：第${attempt}次尝试成功`);
          return content;
        } else {
          throw new Error('未获取到有效内容');
        }
      } catch (error) {
        this.logger.error(`第${attempt}次尝试失败: ${error.message}`);
        await browser.close();

        // 如果不是最后一次尝试，等待一段时间再重试
        if (attempt < maxRetries) {
          this.logger.info(`等待2秒后进行第${attempt + 1}次重试...`);
          await new Promise((resolve) => setTimeout(resolve, 2000));
        }
      }
    }

    this.logger.error(`${word}：所有${maxRetries}次尝试都失败了`);
    return '';
  }

  private solveBaiduContent(html: string, logger?: LogService) {
    const $ = cheerio.load(html);
    const messageContent = $('.ai-entry-block');
    if (messageContent.length > 0) {
      const texts = messageContent
        .filter((_, element) => {
          return $(element).find('.index-module_thinking-steps__C-pm8').length === 0;
        })
        .map((_, element) => $(element).text().trim().replace(/\s/g, ''))
        .get();
      return texts.join('\n');
    } else {
      const message = '未找到目标元素';
      if (logger) {
        logger.warn(message);
      }
      return '';
    }
  }
}
